import Cookies from 'js-cookie'

/**
 * 清除所有 cookie
 */
function clearAllCookie() {
    var date = new Date();
    date.setTime(date.getTime() - 10000);
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;) {
            document.cookie =
                keys[i] + "=; expire=" + date.toGMTString() + "; path=/";
        }
    }
}

/**
 * 设置 cookie
 * @param {string} key 键
 * @param {string} value 值
 * @param {object} expires 过期时间(秒)
 */
function setCookie(key, value, expires) {
    Cookies.set(key, value, expires);
}

/**
 * 获取 cookie
 * @param {string} name 
 */
function getCookie(name) {
    return Cookies.get(name);
}

function setStorage(name, key, val) {
    if (val === 'undefined' || val === 'null') {
        val = null
    }
    var data = {
        data: val,
        time: Date.now(),
        type: typeof val
    }
    window[name].setItem(key, JSON.stringify(data))
}

function getStorage(name, key) {
    var result = window[name].getItem(key)
    if (!result) { return null }
    if (result === 'undefined') { return null }
    result = JSON.parse(result)
    return result.data
}

/**
 * 设置 localStorage
 * @param {string} key
 * @param {any} val
 */
function setLocal(key, val) { return setStorage('localStorage', key, val) }

/**
 * 获取 localStorage
 * @param {string} key
 */
function getLocal(key) { return getStorage('localStorage', key) }

/**
 * 设置 sessionStorage
 * @param {string} key
 * @param {any} val
 */
function setSession(key, val) { return setStorage('sessionStorage', key, val) }

/**
 * 获取 sessionStorage
 * @param {string} key
 */
function getSession(key) { return getStorage('sessionStorage', key) }

/**
 * 清除 localStorage
 * @param {string} key
 */
function delLocal(key) { return window.localStorage.removeItem(key) }

/**
 * 清除 sessionStorage
 * @param {string} key
 */
function delSession(key) { return window.sessionStorage.removeItem(key) }

export default {
    setLocal,         // 设置localStorage
    getLocal,         // 获取localStorage
    delLocal,         // 删除localStorage
    setSession,       // 设置sessionStorage
    getSession,       // 获取sessionStorage
    delSession,       // 删除sessionStorage
    setCookie,       // 设置cookie
    getCookie,       // 获取cookie
    clearAllCookie,  // 删除所有cookie
}